/**
 * 历史记录页面逻辑
 * 负责显示、筛选和管理转换历史记录
 */

class HistoryManager {
    constructor() {
        this.currentPage = 1;
        this.pageSize = 10;
        this.totalRecords = 0;
        this.filteredRecords = [];
        this.allRecords = [];
        
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadHistoryData();
    }

    bindEvents() {
        // 筛选条件变化
        document.getElementById('filterType').addEventListener('change', () => this.applyFilters());
        document.getElementById('filterStatus').addEventListener('change', () => this.applyFilters());
        document.getElementById('filterStartDate').addEventListener('change', () => this.applyFilters());
        document.getElementById('filterEndDate').addEventListener('change', () => this.applyFilters());

        // 清除筛选
        document.getElementById('clearFilters').addEventListener('click', () => this.clearFilters());

        // 导出记录
        document.getElementById('exportHistory').addEventListener('click', () => this.exportHistory());

        // 清空记录
        document.getElementById('clearHistory').addEventListener('click', () => this.clearHistory());
    }

    /**
     * 加载历史数据（模拟数据，实际应该从API获取）
     */
    loadHistoryData() {
        // 模拟历史记录数据
        this.allRecords = [
            {
                id: '1',
                timestamp: '2024-01-15 14:30:25',
                fileName: '银海品项数据.xlsx',
                conversionType: 'yinhai-to-ph1',
                status: 'success',
                totalRecords: 1500,
                successRecords: 1485,
                failedRecords: 15,
                successRate: 99.0
            },
            {
                id: '2',
                timestamp: '2024-01-15 10:15:42',
                fileName: '门诊日志20240115.xlsx',
                conversionType: 'clinic-log',
                status: 'success',
                totalRecords: 2300,
                successRecords: 2300,
                failedRecords: 0,
                successRate: 100.0
            },
            {
                id: '3',
                timestamp: '2024-01-14 16:45:18',
                fileName: 'PH3异地数据.xlsx',
                conversionType: 'ph3-remote',
                status: 'failed',
                totalRecords: 0,
                successRecords: 0,
                failedRecords: 0,
                successRate: 0.0,
                errorMessage: '文件格式不正确'
            },
            {
                id: '4',
                timestamp: '2024-01-14 11:20:33',
                fileName: '大数据文件.xlsx',
                conversionType: 'data-split',
                status: 'success',
                totalRecords: 50000,
                successRecords: 50000,
                failedRecords: 0,
                successRate: 100.0
            },
            {
                id: '5',
                timestamp: '2024-01-13 09:30:15',
                fileName: '银海数据0113.xlsx',
                conversionType: 'yinhai-to-ph1',
                status: 'processing',
                totalRecords: 3200,
                successRecords: 2100,
                failedRecords: 0,
                successRate: 65.6
            }
        ];

        this.applyFilters();
    }

    /**
     * 应用筛选条件
     */
    applyFilters() {
        const typeFilter = document.getElementById('filterType').value;
        const statusFilter = document.getElementById('filterStatus').value;
        const startDate = document.getElementById('filterStartDate').value;
        const endDate = document.getElementById('filterEndDate').value;

        this.filteredRecords = this.allRecords.filter(record => {
            // 类型筛选
            if (typeFilter && record.conversionType !== typeFilter) return false;

            // 状态筛选
            if (statusFilter && record.status !== statusFilter) return false;

            // 日期筛选
            const recordDate = new Date(record.timestamp).toISOString().split('T')[0];
            if (startDate && recordDate < startDate) return false;
            if (endDate && recordDate > endDate) return false;

            return true;
        });

        this.totalRecords = this.filteredRecords.length;
        this.currentPage = 1;
        this.renderTable();
        this.renderPagination();
    }

    /**
     * 清除筛选条件
     */
    clearFilters() {
        document.getElementById('filterType').value = '';
        document.getElementById('filterStatus').value = '';
        document.getElementById('filterStartDate').value = '';
        document.getElementById('filterEndDate').value = '';
        
        this.applyFilters();
    }

    /**
     * 渲染表格
     */
    renderTable() {
        const tbody = document.getElementById('history-table-body');
        
        if (this.filteredRecords.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-muted py-4">
                        <i class="fas fa-inbox fa-3x mb-3 d-block"></i>
                        <h5>暂无符合条件的记录</h5>
                        <p>请调整筛选条件或开始使用转换功能</p>
                    </td>
                </tr>
            `;
            return;
        }

        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = Math.min(startIndex + this.pageSize, this.filteredRecords.length);
        const pageRecords = this.filteredRecords.slice(startIndex, endIndex);

        tbody.innerHTML = pageRecords.map(record => `
            <tr>
                <td>${record.timestamp}</td>
                <td>
                    <div class="d-flex align-items-center">
                        <i class="fas fa-file-excel text-success me-2"></i>
                        ${record.fileName}
                    </div>
                </td>
                <td>
                    <span class="badge bg-info">${this.getTypeDisplayName(record.conversionType)}</span>
                </td>
                <td>
                    ${this.getStatusBadge(record.status, record.errorMessage)}
                </td>
                <td>${record.totalRecords.toLocaleString()}</td>
                <td>
                    <div class="d-flex align-items-center">
                        <div class="progress me-2" style="width: 60px; height: 8px;">
                            <div class="progress-bar ${this.getProgressBarClass(record.successRate)}" 
                                 style="width: ${record.successRate}%"></div>
                        </div>
                        <span class="small">${record.successRate.toFixed(1)}%</span>
                    </div>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        ${record.status === 'success' ? `
                            <button class="btn btn-outline-primary" onclick="historyManager.downloadResult('${record.id}')" 
                                    title="下载结果">
                                <i class="fas fa-download"></i>
                            </button>
                        ` : ''}
                        <button class="btn btn-outline-info" onclick="historyManager.viewDetails('${record.id}')" 
                                title="查看详情">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="historyManager.deleteRecord('${record.id}')" 
                                title="删除记录">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    }

    /**
     * 获取转换类型显示名称
     */
    getTypeDisplayName(type) {
        const typeNames = {
            'yinhai-to-ph1': '银海品项→PH1',
            'clinic-log': '门诊日志转换',
            'ph3-remote': 'PH3异地数据转换',
            'data-split': '数据拆分'
        };
        return typeNames[type] || type;
    }

    /**
     * 获取状态徽章
     */
    getStatusBadge(status, errorMessage = '') {
        const statusConfig = {
            'success': { class: 'bg-success', text: '成功', icon: 'check' },
            'failed': { class: 'bg-danger', text: '失败', icon: 'times' },
            'processing': { class: 'bg-warning', text: '处理中', icon: 'spinner fa-spin' }
        };

        const config = statusConfig[status] || { class: 'bg-secondary', text: '未知', icon: 'question' };
        const tooltip = errorMessage ? `title="${errorMessage}" data-bs-toggle="tooltip"` : '';

        return `
            <span class="badge ${config.class}" ${tooltip}>
                <i class="fas fa-${config.icon} me-1"></i>
                ${config.text}
            </span>
        `;
    }

    /**
     * 获取进度条样式类
     */
    getProgressBarClass(successRate) {
        if (successRate >= 95) return 'bg-success';
        if (successRate >= 80) return 'bg-warning';
        return 'bg-danger';
    }

    /**
     * 渲染分页
     */
    renderPagination() {
        const pagination = document.getElementById('pagination');
        const totalPages = Math.ceil(this.totalRecords / this.pageSize);

        if (totalPages <= 1) {
            pagination.innerHTML = '';
            return;
        }

        let paginationHTML = '';

        // 上一页
        paginationHTML += `
            <li class="page-item ${this.currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="historyManager.goToPage(${this.currentPage - 1})">
                    <i class="fas fa-chevron-left"></i>
                </a>
            </li>
        `;

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || (i >= this.currentPage - 2 && i <= this.currentPage + 2)) {
                paginationHTML += `
                    <li class="page-item ${i === this.currentPage ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="historyManager.goToPage(${i})">${i}</a>
                    </li>
                `;
            } else if (i === this.currentPage - 3 || i === this.currentPage + 3) {
                paginationHTML += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
        }

        // 下一页
        paginationHTML += `
            <li class="page-item ${this.currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="historyManager.goToPage(${this.currentPage + 1})">
                    <i class="fas fa-chevron-right"></i>
                </a>
            </li>
        `;

        pagination.innerHTML = paginationHTML;
    }

    /**
     * 跳转到指定页面
     */
    goToPage(page) {
        const totalPages = Math.ceil(this.totalRecords / this.pageSize);
        if (page < 1 || page > totalPages) return;

        this.currentPage = page;
        this.renderTable();
        this.renderPagination();
    }

    /**
     * 下载转换结果
     */
    downloadResult(recordId) {
        const record = this.allRecords.find(r => r.id === recordId);
        if (!record) return;

        // 这里应该调用实际的下载API
        this.showToast('info', `开始下载 ${record.fileName} 的转换结果`);
        
        // 模拟下载
        const link = document.createElement('a');
        link.href = '#'; // 实际应该是下载链接
        link.download = `转换结果_${record.fileName}`;
        link.click();
    }

    /**
     * 查看详情
     */
    viewDetails(recordId) {
        const record = this.allRecords.find(r => r.id === recordId);
        if (!record) return;

        // 显示详情模态框（这里简化为alert）
        const details = `
转换详情:
时间: ${record.timestamp}
文件: ${record.fileName}
类型: ${this.getTypeDisplayName(record.conversionType)}
状态: ${record.status}
总记录数: ${record.totalRecords}
成功记录: ${record.successRecords}
失败记录: ${record.failedRecords}
成功率: ${record.successRate.toFixed(1)}%
${record.errorMessage ? '\n错误信息: ' + record.errorMessage : ''}
        `;
        
        alert(details);
    }

    /**
     * 删除记录
     */
    deleteRecord(recordId) {
        if (!confirm('确定要删除这条记录吗？')) return;

        this.allRecords = this.allRecords.filter(r => r.id !== recordId);
        this.applyFilters();
        this.showToast('success', '记录已删除');
    }

    /**
     * 导出历史记录
     */
    exportHistory() {
        this.showToast('info', '正在导出历史记录...');
        
        // 这里应该实现实际的导出功能
        setTimeout(() => {
            this.showToast('success', '历史记录导出完成');
        }, 1000);
    }

    /**
     * 清空历史记录
     */
    clearHistory() {
        if (!confirm('确定要清空所有历史记录吗？此操作不可恢复！')) return;

        this.allRecords = [];
        this.applyFilters();
        this.showToast('success', '历史记录已清空');
    }

    /**
     * 显示提示消息
     */
    showToast(type, message) {
        // 创建临时提示框
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} alert-dismissible fade show position-fixed`;
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(alertDiv);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.parentNode.removeChild(alertDiv);
            }
        }, 3000);
    }
}

// 全局实例
let historyManager;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    historyManager = new HistoryManager();
});